/**
 * <pre>
 * Title: 		SystemMonitorImpl.java
 * Project: 	IssueMock
 * Author:		linriqing
 * Create:	 	2009-6-19 下午03:48:48
 * Copyright: 	Copyright (c) 2009
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.common.monitor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hengpeng.common.eds.Event;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.exception.SystemException;
import com.hengpeng.common.exception.TransException;
import com.hengpeng.common.util.ObjectHelper;
import com.hengpeng.common.util.PrintStackTrace;

/**
 * <pre>
 * 系统监视器接口实现
 * 基于缓存服务实现, 依赖于缓存服务, 并需要第三方开发包XStream支持(包含库文件xpp3_min-1.1.3.4.I.jar, xstream-1.0.2.jar).
 * 缓存服务的配置方法请参见以下类型说明:
 * {@linkplain com.hengpeng.common.cache.CacheRepository}
 * {@linkplain com.hengpeng.common.cache.CacheRepository}
 * </pre>
 * @author linriqing
 * @version 1.0, 2009-6-19
 */
public class SystemMonitor
{
	/**
	 * <pre>
	 * 私有静态内部类, 只有当有引用时, 该类才会被装载
	 * </pre>
	 * @author linriqing
	 * @version 1.0, 2009-6-19
	 */
	private final static class LazyInstance
	{
		public static Long currentId = 1L;

		public final static CacheManager singletonManager = CacheManager.create();

		public static final SystemMonitor zzz_foo = new SystemMonitor(false);
	}

	private final static Log logger = LogFactory.getLog(SystemMonitor.class);

	/**
	 * <pre>
	 * 线程安全/单例模式的获取实例方法
	 * 注意:对于Spring来说不是安全的单例, 因为Spring会使用反射调用私有的构造函数...
	 * </pre>
	 * @return 系统监视器接口实现
	 */
	public final static SystemMonitor getInstance()
	{
		return LazyInstance.zzz_foo;
	}

	private SystemMonitor(boolean inject)
	{
		String name = Message.class.getName();
		if (!LazyInstance.singletonManager.cacheExists(name))
		{
			LazyInstance.singletonManager.addCache(new Cache(name, 10000, false, false, 3600, 3600));
		}
		logger.info("成功初始化系统监视器接口实现.");
	}

	public void addCacheMessage(Message message)
	{
		Cache cache = LazyInstance.singletonManager.getCache(Message.class.getName());
		if (cache != null)
		{
			Element element = new Element(String.valueOf(message.getId()), message);
			cache.put(element);
		}

		synchronized (LazyInstance.currentId)
		{
			if (LazyInstance.currentId < message.getId())
			{
				LazyInstance.currentId = message.getId();
			}
		}
	}

	public void addMessage(Event event)
	{
		addCacheMessage(new Message(new Date(), event.getSummary(), ObjectHelper.toJson(event)));
	}

	public void addMessage(Exception exception)
	{
		Message message = new Message(new Date(), "系统未知异常, 错误消息{" + exception.getMessage() + "}.",
				PrintStackTrace.getStackTrace(exception));
		addCacheMessage(message);
	}

	public void addMessage(Message message)
	{
		addCacheMessage(message);
	}

	public void addMessage(ServiceResult<?> result)
	{
		if (result.getIsSuccess())
		{
			if (result.getReturnValue() != null)
			{
				Message message = new Message(new Date(), "调用服务接口结果消息, 代码{" + result.getCode() + "}, 描述{"
						+ result.getMessage() + "}.", ObjectHelper.toPropertiesString(result.getReturnValue()));
				addCacheMessage(message);
			}
			else
			{
				Message message = new Message(new Date(), "调用服务接口结果消息, 代码{" + result.getCode() + "}, 描述{"
						+ result.getMessage() + "}.", "");
				addCacheMessage(message);
			}
		}
		else
		{
			if (result.getException() != null)
			{
				Message message = new Message(new Date(), "调用服务接口结果消息, 代码{" + result.getCode() + "}, 描述{"
						+ result.getMessage() + "}.", PrintStackTrace.getStackTrace(result.getException()));
				addCacheMessage(message);
			}
			else
			{
				if (result.getReturnValue() != null)
				{
					Message message = new Message(new Date(), "调用服务接口结果消息, 代码{" + result.getCode() + "}, 描述{"
							+ result.getMessage() + "}.", ObjectHelper.toPropertiesString(result.getReturnValue()));
					addCacheMessage(message);
				}
				else
				{
					Message message = new Message(new Date(), "调用服务接口结果消息, 代码{" + result.getCode() + "}, 描述{"
							+ result.getMessage() + "}.", "");
					addCacheMessage(message);
				}
			}
		}
	}

	public void addMessage(SystemException exception)
	{
		Message message = new Message(new Date(), "运行时异常, 错误码{" + exception.getExceptionCode() + "}" + ", 错误消息{"
				+ exception.getExceptionMsg() + "}.", PrintStackTrace.getStackTrace(exception));
		addCacheMessage(message);
	}

	public void addMessage(TransException exception)
	{
		Message message = new Message(new Date(), "应用异常, 错误码{" + exception.getExceptionCode() + "}" + ", 错误消息{"
				+ exception.getExceptionMsg() + "}.", PrintStackTrace.getStackTrace(exception));
		addCacheMessage(message);
	}

	public Date getCurrentDate()
	{
		return new Date();
	}

	public long getCurrentId()
	{
		return LazyInstance.currentId;
	}

	public List<Message> getLastMessage(long startId)
	{
		List<Message> messages = new ArrayList<Message>();
		long lastid = LazyInstance.currentId;
		long firstId = startId + 1;
		for (long i = firstId; i <= lastid; i++)
		{
			Cache cache = LazyInstance.singletonManager.getCache(Message.class.getName());
			Element element = cache.get(String.valueOf(i));
			if (element != null)
			{
				messages.add((Message) element.getObjectValue());
			}
		}
		return messages;
	}

	public Message getMessage(long messageId)
	{
		Cache cache = LazyInstance.singletonManager.getCache(Message.class.getName());
		Element element = cache.get(String.valueOf(messageId));
		if (element != null)
		{
			return (Message) element.getObjectValue();
		}
		else
		{
			return null;
		}
	}
}
